package com.ycsj.common.mvp;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ycsj.common.base.BusInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;

import butterknife.ButterKnife;

/**
 * 懒加载的基类Fragment
 * Created by Administrator on 2018/10/31 0031.
 */

public abstract class BaseMvpFragment<V, T extends BasePresenter<V>> extends Fragment {

    //跟布局
    protected View rootView;

    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";

    //表示p层的引用
    public T p;

    /**
     * 标记已加载完成，保证懒加载只能加载一次
     */
    private boolean hasLoaded = false;
    /**
     * 标记Fragment是否已经onCreate
     */
    private boolean isCreated = false;
    /**
     * 界面对于用户是否可见
     */
    private boolean isVisibleToUser = false;

    /**
     * 防止点击过快的时间间隔
     */
    public static final long NO_DOUBLE_CLICK_TIME = 500;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        rootView = View.inflate(getContext(), getLayoutId(), null);


        //创建Presenter并进行V层的绑定
        p = createPresenter();
        p.attachView((V) this);

        //绑定视图
        ButterKnife.bind(this, rootView);

        //注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        return rootView;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(rootView, savedInstanceState);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);

            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (isSupportHidden) {
                ft.hide(this);
            } else {
                ft.show(this);
            }
            ft.commit();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
    }

    /**
     * 返回布局ID的方法
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 提供给子类创建presenter的方法
     *
     * @return
     */
    protected abstract T createPresenter();

    /**
     * 初始化方法
     */
    protected void init(View view, Bundle savedInstanceState) {
        isCreated = true;//注：关键步骤
        lazyLoad(view, savedInstanceState);
    }


    /**
     * 懒加载方法，获取数据什么的放到这边来使用，在切换到这个界面时才进行网络请求
     */
    private void lazyLoad(View view, Bundle savedInstanceState) {

        //如果该界面不对用户显示、已经加载、fragment还没有创建，
        //三种情况任意一种，不获取数据
        if (!isVisibleToUser || hasLoaded || !isCreated) {
            return;
        }
        lazyInit(view, savedInstanceState);
        hasLoaded = true;//注：关键步骤，确保数据只加载一次
    }

    /**
     * 子类必须实现的方法，这个方法里面的操作都是需要懒加载的
     */
    public abstract void lazyInit(View view, Bundle savedInstanceState);


    /**
     * 监听界面是否展示给用户，实现懒加载
     * 这个方法也是网上的一些方法用的最多的一个，我的思路也是这个，不过把整体思路完善了一下
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisibleToUser = isVisibleToUser;//注：关键步骤
        super.setUserVisibleHint(isVisibleToUser);
        lazyLoad(rootView, null);
    }


    /**
     * 防止按钮重复点击的方法
     */
    protected boolean isDoubleClick(View v) {
        Object tag = v.getTag(v.getId());
        long beforeTimemiles = tag != null ? (long) tag : 0;
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        v.setTag(v.getId(), timeInMillis);
        return timeInMillis - beforeTimemiles < NO_DOUBLE_CLICK_TIME;
    }

    /**
     * 显示加载布局的方法,隐藏内容布局
     */
    protected void showLoading(View rlLoading, View contentView) {
        if (rlLoading != null && rlLoading.getVisibility() != View.VISIBLE) {
            rlLoading.setVisibility(View.VISIBLE);
        }

        if (contentView != null && contentView.getVisibility() != View.GONE) {
            contentView.setVisibility(View.GONE);
        }

    }

    /**
     * 隐藏加载布局,显示内容布局
     */
    protected void showContent(View rlLoading, View contentView) {
        if (rlLoading != null && rlLoading.getVisibility() != View.GONE) {
            rlLoading.setVisibility(View.GONE);
        }

        if (contentView != null && contentView.getVisibility() != View.VISIBLE) {
            contentView.setVisibility(View.VISIBLE);
        }
    }


    /**
     * EventBus的接受事件的方法
     *
     * @param busInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busEvent(BusInfo busInfo) {

    }

    @Override
    public void onDestroy() {
        //解绑P层的操作
        if (null != p) {
            p.detachView();
        }

        EventBus.getDefault().unregister(this);
        isCreated = false;
        hasLoaded = false;
        super.onDestroy();
    }

}
